﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Data.OleDb;
using spbtzb;
using System.Text;
using System.IO;

public partial class Back_FileList : System.Web.UI.Page
{
    protected string strConnection = spbtzb.ConString.ConnString;
    #region Field

    private Boolean session_Logined
    {
        set
        {
            Session["Logined"] = value;
        }
        get
        {
            return Session["Logined"] == null ? false : Convert.ToBoolean(Session["Logined"]);
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

        if (session_Logined == false)
        {
            Response.Redirect("Login.aspx?ErrorMessage=" + "您未登录，请在此登录");
        }
        if (!IsPostBack)
        {
            BindDataListInit();
        }

    }

    private void BindDataListInit()
    {
        DataTable dt = AccessHelper.ExecuteDataTable(strConnection, CommandType.Text,
            "SELECT * FROM FileList Order By ID DESC");

        if ( dt.Rows.Count == 0)// dt == null ||
        {
            btn_sumit.Visible = false;
            ipt_HdnSelectedValues.Value = ",";
        }
        else
        {
            btn_sumit.Visible = true;
            StringBuilder sb = new StringBuilder();
            sb.Append(",");
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["IsDisplay"] != null && Convert.ToBoolean(dr["IsDisplay"]) == true
                    && dr["ID"] != null)
                {
                    sb.Append(dr["ID"].ToString() + ",");
                }
            }
            if (sb.Length > 0)
            {
                this.ipt_HdnSelectedValues.Value = sb.Remove(sb.Length - 1, 1).ToString(); // 干掉最后一个逗号
            }
        }
        gvDict.DataSource = dt;
        gvDict.DataBind();
    }



    private void BindDataList()
    {
        DataTable dt = AccessHelper.ExecuteDataTable(strConnection, CommandType.Text,
             "SELECT * FROM FileList Order By ID DESC");

        if (dt.Rows.Count == 0) // dt == null || 
        {
            btn_sumit.Visible = false;
            ipt_HdnSelectedValues.Value = ",";
        }
        else
        {
            btn_sumit.Visible = true;
        }
        gvDict.DataSource = dt;
        gvDict.DataBind();
    }

    protected void gvDict_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvDict.PageIndex = e.NewPageIndex;
        BindDataList();
    }


    protected void gvDict_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItemIndex < 0) return;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // 来个垃圾办法解决问题
            HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)e.Row.FindControl("IsDisplayCheckBox");
            if (ChkSelected == null) return;
            String strid = ChkSelected.Value;
            String strIDs = this.ipt_HdnSelectedValues.Value;
            String strIDsEx = strIDs.TrimStart(',');
            String[] ids = strIDsEx.Split(',');
          
            //foreach (String id in ids)
            //{
            //    if (strid == id)
            //    {
            //        ChkSelected.Checked = true;
            //        return;
            //    }
            //}
            // replaced by:
            if (ids.Contains(strid))
            {
                ChkSelected.Checked = true;
            }
        }
    }

    protected void gvDict_RowCommand(object sender, GridViewCommandEventArgs e)
    {  
        String strID = e.CommandArgument.ToString();
        switch (e.CommandName)
        {
            case "DeleteContent": 
                //ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(LinkButton), "tip", "confirm(您真的要删除这篇留言吗？);", true);
                OleDbConnection conn = new OleDbConnection(strConnection);
                conn.Open();
                OleDbTransaction trans = conn.BeginTransaction();

                try
                {
                    string strFilePath = "~/filesUpload/" + AccessHelper.ExecuteScalar(trans, CommandType.Text, "SELECT FileUrl FROM FileList WHERE [ID] =" + strID);
                    File.Delete(Server.MapPath(strFilePath));
                    int iret = AccessHelper.ExecuteNonQuery(trans, CommandType.Text, "DELETE FROM FileList WHERE [ID] =" + strID); //no judgement = =!
                    
                    if (iret <= 0)
                    {
                        throw new Exception("删除内容失败");                       
                    }
                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    //ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作失败，请重新操作或联系管理员！');", true);
                   
                    //Response.Redirect("~/Common/ErrorPage.aspx?ErrorMessage=" + "文件上传失败，请重新操作或请联系管理员!");
                    Page.RegisterClientScriptBlock("tip", "<script>alert('操作失败，请重新操作或联系管理员！')</script>");
                    return;
                }
                finally
                {
                    conn.Close();
                }
                Page.RegisterClientScriptBlock("tip", "<script>alert('操作成功！')</script>");                
                //ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('删除操作成功!');", true);
                String strSelected = this.ipt_HdnSelectedValues.Value;
                String strTemp = "," + strID;
                if (strSelected.Contains(strTemp))
                {
                    this.ipt_HdnSelectedValues.Value = strSelected.Replace(strTemp, "");
                }
                BindDataList();

                break;

            case "Download":
                string strFilePath2 = Server.MapPath("~/filesUpload/") + AccessHelper.ExecuteScalar(strConnection, CommandType.Text, "SELECT FileUrl FROM FileList WHERE [ID] =" + strID);
                  FileInfo fi = new FileInfo(strFilePath2);
                  //判断文件是否存在
                  if (fi.Exists)
                  {
                      //将文件保存到本机上
                      Response.Clear();
                      Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fi.Name));
                      Response.AddHeader("Content-Length", fi.Length.ToString());
                      Response.ContentType = "application/octet-stream";
                      Response.Filter.Close();
                      Response.WriteFile(fi.FullName);
                      Response.End();
                  }   
                  else
                  {
                      Page.RegisterClientScriptBlock("tip", "<script>alert('该文件不存在，请重新选择或联系管理员！')</script>");
                  }
                break;

            default:
                break;
        }
    }
    protected void btn_sumit_Click(object sender, EventArgs e)
    {
        string SQL;
        int iret = 0;      
        String strIDs = this.ipt_HdnSelectedValues.Value;
        //String strIDsEx = strIDs.TrimStart(',');
        //String[] ids = strIDsEx.Split(',');
        // replaced by:
        Char[] sperateChars = new Char[] { ',' };
        String[] ids = strIDs.Split(sperateChars, StringSplitOptions.RemoveEmptyEntries);
        SQL = "UPDATE FileList SET IsDisplay=false ";
        OleDbConnection conn = new OleDbConnection(strConnection);
        conn.Open();
        OleDbTransaction trans = conn.BeginTransaction();
        try
        {
            iret = AccessHelper.ExecuteNonQuery(trans, CommandType.Text, SQL);    
            foreach (String id in ids)
            {
                SQL = "UPDATE FileList SET IsDisplay=true WHERE [ID] =" + Convert.ToInt32(id).ToString();
                iret = AccessHelper.ExecuteNonQuery(trans, CommandType.Text, SQL); 
            }
            trans.Commit();
            Page.RegisterClientScriptBlock("tip", "<script>alert('操作成功！')</script>");       
            //ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作成功！');", true);
        }
        catch
        {

            Page.RegisterClientScriptBlock("tip", "<script>alert('操作失败，请重新操作或联系管理员！')</script>");       
           // ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作失败，请重新操作或联系管理员！');", true);
            trans.Rollback();
        }
        finally
        {
            conn.Close();
        }      
    }

}// cs
